package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.sky.constant.MessageConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.ShopService;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;


    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用个微信接口，获取当前用户的openid
        String openid = getOpenid(userLoginDTO);

        //判断openid是否为空，为空表示登录失败，抛出异常
        if (StrUtil.isBlank(openid)) {
            throw  new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户
        User user = userMapper.queryUserByOpenID(openid);
        if (user == null) {
            //如果是新用户，自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);
        }

        //返回单个用户对象
        return user;
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String, String> map = new HashMap<>();
        map.put(WeChatConstant.APPID, weChatProperties.getAppid());
        map.put(WeChatConstant.SECRET, weChatProperties.getSecret());
        map.put(WeChatConstant.JS_CODE, userLoginDTO.getCode());
        map.put(WeChatConstant.GRANT_TYPE, WeChatConstant.GRANT_TYPE_VALUE);

        String json = HttpClientUtil.doGet(WeChatConstant.LOGIN_URL, map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = (String)jsonObject.get(WeChatConstant.OPENID);
        return openid;
    }
}
